// pages/profile/profile.js
import auth from '../../utils/auth'
const app = getApp()

Page({
  data: {
    userInfo: {},
    loading: false,
    loginPrompted: false
  },

  onLoad(options) {
    this.initPage()
  },

  onShow() {
    // 同步tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }

    // 每次显示页面时刷新用户信息
    this.loadUserInfo()
  },

  // 初始化页面
  initPage() {
    this.loadUserInfo()
  },

  // 加载用户信息
  async loadUserInfo() {
    // 登录检查：基于 token 判断，避免已取到token但尚未拉取userInfo时反复提示
    const hasToken = app.globalData.token || wx.getStorageSync('token')
    if (!hasToken) {
      if (!this.data.loginPrompted) {
        this.setData({ loginPrompted: true })
        auth.requireLogin()
      }
      return
    }
    try {
      this.setData({ loading: true })
      
      // 从全局数据获取用户信息
      const globalUserInfo = app.globalData.userInfo
      if (globalUserInfo) {
        const normalized = {
          ...globalUserInfo,
          nickname: globalUserInfo.nickname || globalUserInfo.nickName || '',
          avatar: globalUserInfo.avatar || globalUserInfo.avatar_url || globalUserInfo.avatarUrl || ''
        }
        this.setData({ userInfo: normalized })
      } else {
        // 尝试从本地存储获取
        const localUserInfo = wx.getStorageSync('userInfo')
        if (localUserInfo) {
          const normalized = {
            ...localUserInfo,
            nickname: localUserInfo.nickname || localUserInfo.nickName || '',
            avatar: localUserInfo.avatar || localUserInfo.avatar_url || localUserInfo.avatarUrl || ''
          }
          this.setData({ userInfo: normalized })
        } else {
          // 优先从后端获取用户资料
          try {
            const serverProfile = await auth.getUserProfile()
            if (serverProfile) {
              // 统一字段为 nickname / avatar
              const normalized = {
                id: serverProfile.id || serverProfile.user_id || '',
                nickname: serverProfile.nickname || serverProfile.nickName || '',
                avatar: serverProfile.avatar || serverProfile.avatar_url || serverProfile.avatarUrl || ''
              }
              this.setData({ userInfo: normalized })
              wx.setStorageSync('userInfo', normalized)
              app.globalData.userInfo = normalized
            } else {
              await this.getWechatUserInfo()
            }
          } catch(e) {
            // 回退到微信授权
            await this.getWechatUserInfo()
          }
        }
      }
      
    } catch (error) {
      console.error('加载用户信息失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 获取微信用户信息
  async getWechatUserInfo() {
    try {
      const userProfile = await wx.getUserProfile({
        desc: '用于完善个人资料'
      })
      
      if (userProfile) {
        const userInfo = {
          nickName: userProfile.userInfo.nickName,
          avatarUrl: userProfile.userInfo.avatarUrl,
          // 统一字段
          nickname: userProfile.userInfo.nickName,
          avatar: userProfile.userInfo.avatarUrl,
          id: '123456' // TODO: 从后端获取实际用户ID
        }
        
        this.setData({ userInfo })
        
        // 保存到本地存储
        wx.setStorageSync('userInfo', userInfo)
        app.globalData.userInfo = userInfo
      }
      
    } catch (error) {
      console.log('用户取消授权或获取信息失败')
    }
  },

  // 编辑资料
  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit'
    })
  },

  // 跳转到个人预约记录
  async navigateToPersonalReservations() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/profile/reservations'
    })
  },

  // 跳转到团队预约记录
  async navigateToTeamReservations() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({ url: '/pages/reservation/list' })
  },

  // 跳转到活动申请记录
  async navigateToActivityApplications() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({ url: '/pages/profile/activities' })
  },

  // 跳转到常用观众信息
  async navigateToVisitorInfo() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/profile/common-visitors'
    })
  },

  // 跳转到意见信箱
  async navigateToFeedback() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/profile/feedback'
    })
  },

  // 跳转到联系我们
  navigateToContact() {
    wx.navigateTo({
      url: '/pages/profile/contact'
    })
  },

  // 跳转到宣讲团报名
  async navigateToVolunteer() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/volunteer/apply'
    })
  },

  // 跳转到订阅消息
  async navigateToSubscription() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/profile/subscribe-settings'
    })
  },

  // 跳转到个人设置
  async navigateToSettings() {
    const ok = await app.checkAuth()
    if (!ok) return
    wx.navigateTo({
      url: '/pages/profile/settings'
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '南京中医药大学校史馆',
      path: '/pages/index/index',
      imageUrl: '/images/share-logo.png'
    }
  }
})